#-------------------------------------------------------------------------------
# Name:        webfrontend.py
# Purpose:     Use Cherrypy server to upload files for conversion
#
# Authors:     Glenn Ramsey <glenn.ramsey@slidespeech.com>
#              John Graves <john.graves@slidespeech.com>
#
# Created:     19 April 2012
# Modifie:     30 October 2012
# Copyright:   (c) Slidespeech Ltd 2012
# Licence:     MIT license
#-------------------------------------------------------------------------------

import os
import subprocess
import gettext
import cherrypy
#from cherrypy.lib.static import serve_file # dependency
import time

from  converter import *
import sys
from jinja2 import Environment, FileSystemLoader

from zip_to_pdf_converter import *
from pdf_to_png_converter import *
from zip_to_xml_converter import *
from xml_to_notes_converter import *
from notes_to_QAR_converter import *
from qar_to_audio_converter import *
from html5_converter import *
from png_to_notes_converter import *

__version__ = "2012-11-01"

lang = "en"


if sys.platform.startswith("linux"):
    pass
elif sys.platform.startswith("darwin"):
    pass
elif sys.platform.startswith("win"):
    from ppt_to_png_and_notes_converter import *
else:
    raise NotImplementedError()

gettext.bindtextdomain('slidespeech', os.path.join(os.getcwd(), 'locale'))
gettext.textdomain('slidespeech')
_ = gettext.gettext

def uploadPresentationFile(version, language, errorMessage):
    """Display the 'Upload presentation file' form."""
    env = Environment(loader=FileSystemLoader('templates'), extensions=['jinja2.ext.i18n'])
    domain = 'slidespeech'
    try:
        trans = gettext.translation(domain, os.path.join(os.getcwd(), 'locale'), [language])
    except IOError:
        # This probably means that there is no .mo file.
        # FIXME: This needs to be generated during installation
        trans = gettext.NullTranslations()

    env.install_gettext_translations(trans)
    template = env.get_template('uploadPresentationFile.html')
    return template.render(LANGUAGE=language,
                           errorMessage=errorMessage,
                           version=version,
                           ttsURL=AudioConfig.ttsURL,
                           ttsEngine=AudioConfig.ttsEngine)



class UploadPage():
    def index(self):
        # FIXME: where do we get the user's language preference from?
        return uploadPresentationFile(__version__, lang, None)

    index.exposed = True


    # ----------------------------------------------------------------

    def timestamp(self):
        """Returns YYYYMMDD.HH.MM.SS_xxxxxx where xxxxxx is the fractional part of the day"""
        return time.strftime("%Y%m%d.%H.%M.%S_")+("%f" % time.time()).split(".")[1]

    # ----------------------------------------------------------------

    def uploadFile(self, myFile=None, email=None, title=None, author=None):
        if email==None or 0==len(email.strip()):
            return uploadPresentationFile(__version__, lang, _("Please supply your e-mail address."))
        if -1==email.find('@'):
            return uploadPresentationFile(__version__, lang, _("Please supply a valid e-mail address."))
        if myFile is None:
            return uploadPresentationFile(__version__, lang, _("Please supply a presentation file."))
        (sourcepath, PresentationFile) = os.path.split(myFile.filename)
        (PresentationFileStem, PresentationFileExtension) = os.path.splitext(PresentationFile)
        PresentationFileExtension = PresentationFileExtension.lower()
        if not (PresentationFileExtension in (".ppt",".pptx",".odp",".png",".zip",".pdf")):
            return uploadPresentationFile(__version__, lang, _("Please select a .ppt .pptx .odp .pdf or .zip file."))

        # Create time stamped temp directory
        publishedTime = self.timestamp()
        tempDir = os.getcwd()+os.sep+"static"+os.sep+publishedTime+os.sep
        os.makedirs(tempDir)

        # Save input into new directory as temp.xxx
        tempFile = os.path.join(tempDir,"temp"+PresentationFileExtension)
        savedInptFile = open(tempFile,"wb")
        while True:
            data = myFile.file.read(8192)
            if not data:
                break
            savedInptFile.write(data)
        savedInptFile.close()

        if PresentationFileExtension in ('.ppt','.pptx'):
            i = PPTToPNGAndNotesConverter( tempDir, tempFile, "en", tempDir=tempDir)
            n = NotesToQARConverter(i)
        if PresentationFileExtension == '.pdf':
            p = PdfToPngConverter( tempDir, pdfFile=tempFile, pngPath=tempDir )
            n = PngToNotesConverter(p)
        if PresentationFileExtension == '.zip':
            p = ZipToPDFConverter( os.path.join(tempDir,tempFile), pdfPath=tempDir)
            i = PdfToPngConverter( pdfPath=os.path.join(tempDir,'CONTENTS'), pngPath=tempDir, previous=p )
            x = ZipToXMLConverter( os.path.join(tempDir,tempFile), xmlPath=tempDir, previous=i)
            n = XmlToNotesConverter( xmlPath=os.path.join(tempDir,'CONTENTS'), previous=x)
        q = NotesToQARConverter(n)
        a = QARToAudioConverter(q)
        h = HTML5Converter('templates/includes',a)
        h.convert()
        url = 'file://localhost/'+h.tempDir()+'/html/index.html'
        webbrowser.open(url)

        return uploadPresentationFile(__version__, lang, None)

#            # Sequence the script and post records to SQL database
#            seq = scriptParser.parseText(text)
#            shutil.copyfile("output.json",tempDir+"output.json")
##            for i, question in enumerate(seq.sequence):
##                shutil.copyfile("sample.png",tempDir+"Slide"+str(i)+".png")
#
#            outputFile = ZipFile(tempDir+"output.zip",'w')
#            savePath = os.getcwd()
#            os.chdir(tempDir)
#            tempPathDirectoryList = os.listdir('.')
#            for fileName in tempPathDirectoryList:
#                fileNameStem, fileExtension = os.path.splitext(fileName)
#                if fileExtension in (".png") or fileName=="output.json":
#                    outputFile.write(fileName)
#            outputFile.close()
#            os.chdir(savePath)
#
#            connection = sqlite3.connect('slides.db')
#            cursor = connection.cursor()
#            slideList = []
#            for question in seq.sequence:
#                staticAt = tempDir.find('static')
#                if 0<len(question.linkToShow):
#                    slideList.append([tempDir[staticAt:]+question.linkToShow,
#                                 question.unparsedQuestion])
#                else:
#                    slideList.append(["",
#                                 question.unparsedQuestion])
#
#            #Replace records (if any) with renumbered slides
#            cursor.execute('DELETE FROM slides WHERE tag=?', (PresentationFileStem,))
#            for i in range(0,len(slideList)):
#                cursor.execute('INSERT INTO slides VALUES (?,?,?,?,?)',
#                              (PresentationFileStem,email,i,slideList[i][0],slideList[i][1]))
#            connection.commit()
#            self.publishSlidesToHtml(tag=PresentationFileStem, email=email,publishedTime=publishedTime)
#            scriptList = [(PresentationFileStem,email,publishedTime)]
#            return forms.listScripts(__version__,
#                                     "Presentation published. Check e-mail.",
#                                     scriptList,
#                                     PresentationFileStem,
#                                     publishedTime,
#                                     email)
#
##            return forms.scriptInputFormWithMessage(__version__,
##                                                    "",
##                                                    PresentationFileStem,
##                                                    slideList,
##                                                    "",
##                                                    False,
##                                                    "",
##                                                    email)
    uploadFile.exposed = True

if __name__ == '__main__':
    # CherryPy always starts with app.root when trying to map request URIs
    # to objects, so we need to mount a request handler root. A request
    # to '/' will be mapped to HelloWorld().index().
    cherrypy.config.update({'server.socket_host': '127.0.0.1',
                        'server.socket_port': 10080,
                        'server.thread_pool': 10,
                       })
    config = {'/': {'tools.staticdir.root': os.path.abspath(os.curdir)},
              '/static':{'tools.staticdir.on':True,
                         'tools.staticdir.dir':"static"}}
    cherrypy.quickstart(UploadPage(), config=config)
